package com.hankol.community.fragment

import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.Rect
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.text.TextUtils
import android.view.Gravity
import android.view.MotionEvent
import android.view.View
import android.view.View.OnTouchListener
import android.widget.PopupWindow
import android.widget.SeekBar
import androidx.lifecycle.Observer
import com.baselibrary.BaseConstant
import com.baselibrary.MessageBus
import com.baselibrary.activity.BaseFragment
import com.baselibrary.bean.TimelineInfoData
import com.baselibrary.extension.checkNotNull
import com.baselibrary.livedata.LiveDataBus
import com.baselibrary.livedata.LiveDataKey
import com.baselibrary.router.ActivityRouter
import com.baselibrary.utils.*
import com.baselibrary.utils.EventBusUtils.sendNotifyParams
import com.baselibrary.view.share.SharePopupWindow
import com.hankol.community.R
import com.hankol.community.VideoDetailsActivity
import com.hankol.community.databinding.FragmentVideoDetailsBinding
import com.hankol.community.databinding.PopupCommentlistBinding
import com.hankol.community.viewmodel.VideoDetailsViewModel
import com.like.LikeButton
import com.like.OnLikeListener
import com.okhttp.comment.BaseCommentAdapter
import com.okhttp.comment.CommentBean
import com.okhttp.comment.CommentConstant
import com.okhttp.comment.CommentReplyBean
import com.scwang.smartrefresh.layout.api.RefreshLayout
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener
import com.tencent.rtmp.TXVodPlayer
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.util.*


/**
 * @description 新版视频详情
 * @author 关忆北、
 * @time 2022/4/10 1:45 下午
 */
class VideoDetailsFragment : BaseFragment(), View.OnClickListener, OnRefreshLoadMoreListener, VideoDetailsActivity.IActivityResult, VideoDetailsViewModel.OnPublishCompleteListener {
    private lateinit var mActivity: VideoDetailsActivity
    private lateinit var mBinding: FragmentVideoDetailsBinding
    private lateinit var mViewModel: VideoDetailsViewModel
    private lateinit var mVodPlayer: TXVodPlayer
    private var mPage = 1
    private var browseNum = 0
    private var mVideoId: Int = 0
    private var mSlidePro: Int = 0
    private var isOpenComment = false
    private var userId: Int = 0
    private var isDoubleClick = false
    private var mNetErrorView: View? = null
    private var topCommentId: Long = 0
    var index = -1
    var data: TimelineInfoData.ClientTimeline? = null
    private var mPopupBinding: PopupCommentlistBinding? = null
    private var mCommentBean: CommentBean.DataBean? = null
    private var mCommentPopup: PopupWindow? = null
    private var mNetErrorViewPopup: PopupWindow? = null
    private var mSharePopupWindow: SharePopupWindow? = null
    private var playSpeedList = mutableListOf<String>()
    private val tHandler = Handler { msg: Message ->
        when (msg.what) {
            mViewModel.UP_PLAYER -> mBinding.ivDetailsPlay.visibility = View.GONE
        }
        false
    }

    companion object {
        fun newInstance(id: Int, index: Int, browseNum: Int, isOpenComment: Boolean?, topCommentId: Long): VideoDetailsFragment {
            val fragment = VideoDetailsFragment()
            val args = Bundle()
            args.putInt("id", id)
            args.putInt("browseNum", browseNum)
            args.putInt("index", index)
            args.putBoolean("isOpenComment", isOpenComment!!)
            args.putLong("topCommentId", topCommentId)
            fragment.arguments = args
            return fragment
        }

    }

    override fun init() {
        playSpeedList.add("1.0x")
        playSpeedList.add("1.5x")
        playSpeedList.add("2.0x")
        playSpeedList.add("0.5x")
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this)
        }

        mVodPlayer = TXVodPlayer(context)
        mActivity = activity as VideoDetailsActivity
        mBinding = getDataBinding<FragmentVideoDetailsBinding>()
        mViewModel = getFragmentViewModelProvider(this).get(VideoDetailsViewModel::class.java)

        getBundleData()
        initObserve()
        loadData()
        initListener()
    }

    override fun getLayoutId(): Int {
        return R.layout.fragment_video_details
    }


    private fun getBundleData() {
        bundle?.let {
            if (it.containsKey("id")) mVideoId = it.getInt("id")
            if (it.containsKey("browseNum")) browseNum = it.getInt("browseNum")
            if (it.containsKey("isOpenComment")) isOpenComment = it.getBoolean("isOpenComment")
            if (it.containsKey("topCommentId")) topCommentId = it.getLong("topCommentId")
            if (it.containsKey("index")) index = it.getInt("index", -1)
        }
    }

    @SuppressLint("ClickableViewAccessibility") private fun initListener() {
        mActivity.setCallback(this)
        mBinding.back.setOnClickListener(this)
        mBinding.llDetailsLike.setOnClickListener(this)
        mBinding.ivDetailsHead.setOnClickListener(this)
        //mBinding.llDetailsShow.setOnClickListener(this)
        mBinding.llDetailsShare.setOnClickListener(this)
        mBinding.tvDetailsTopic.setOnClickListener(this)
        mBinding.ivDetailsFollow.setOnClickListener(this)
        mBinding.tvDetailsComment.setOnClickListener(this)
        mBinding.rlDetailsComment.setOnClickListener(this)
        mBinding.tvDetailsPlaySpeed.setOnClickListener(this)
        mBinding.ivDetailsFullscreen.setOnClickListener(this)

        mBinding.sbDetailsDpeed.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
            override fun onProgressChanged(seekBar: SeekBar, p1: Int, p2: Boolean) {
                mSlidePro = seekBar.progress
            }

            override fun onStartTrackingTouch(p0: SeekBar?) {
            }

            override fun onStopTrackingTouch(p0: SeekBar?) {
                //手指抬起获取当前SeekBar进度
                mVodPlayer.seek(mSlidePro / 1000)
                mVodPlayer.resume()
            }

        })
        mBinding.tlDetailsDoubleclick.setOnDownClickListener { isLike ->
            if (!isLike) { //控制是点赞还是暂停
                mBinding.ivDetailsPlay.visibility = if (mBinding.ivDetailsPlay.isShown) View.GONE else View.VISIBLE
                if (mBinding.ivDetailsPlay.isShown) {
                    mViewModel.hidePlayerView(tHandler)
                }
            } else {
                if (!isDoubleClick) {
                    //双击屏幕 判定为点赞
                    mViewModel.reqSupport(true, 4, mVideoId)
                }
            }
        }
        mBinding.llDetailsDpeed.setOnTouchListener(object : OnTouchListener {
            @SuppressLint("ClickableViewAccessibility")
            override fun onTouch(p0: View, event: MotionEvent): Boolean {
                val seekRect = Rect()
                mBinding.sbDetailsDpeed.getHitRect(seekRect)

                if (event.y >= seekRect.top - 50 && event.y <= seekRect.bottom + 50) {
                    val y = (seekRect.top + seekRect.height() / 2).toFloat()
                    var x: Float = event.x - seekRect.left
                    if (x < 0) {
                        x = 0f
                    } else if (x > seekRect.width()) {
                        x = seekRect.width().toFloat()
                    }
                    val me = MotionEvent.obtain(event.downTime, event.eventTime, event.action, x, y, event.metaState)
                    return mBinding.sbDetailsDpeed.onTouchEvent(me)
                }
                return false

            }
        })
        mBinding.ivDetailsGive.setOnLikeListener(object : OnLikeListener {
            override fun liked(likeButton: LikeButton?) {
                //点赞
                if (!SpUtils.getInstance().isLogin) {
                    AppManager.getAppManager().openLoginPage()
                    return
                }
                mBinding.ivDetailsGive.isEnabled = false
                mViewModel.reqSupport(true, 4, mVideoId)
            }

            override fun unLiked(likeButton: LikeButton?) {
                if (!SpUtils.getInstance().isLogin) {
                    AppManager.getAppManager().openLoginPage()
                    return
                }
                mBinding.ivDetailsGive.isEnabled = false
                //取消点赞
                mViewModel.reqSupport(false, 4, mVideoId)
            }
        })

        mBinding.ivDetailsCollection.setOnLikeListener(object : OnLikeListener {
            override fun liked(likeButton: LikeButton?) {

                //收藏
                if (!SpUtils.getInstance().isLogin) {
                    AppManager.getAppManager().openLoginPage()
                    return
                }
                // 进行点击事件后的逻辑操作
                mBinding.ivDetailsCollection.isEnabled = false
                mViewModel.reqCollection(true, 4, mVideoId.toLong())
            }

            override fun unLiked(likeButton: LikeButton?) {
                //取消收藏
                if (!SpUtils.getInstance().isLogin) {
                    AppManager.getAppManager().openLoginPage()
                    return
                }
                mBinding.ivDetailsCollection.isEnabled = false
                // 进行点击事件后的逻辑操作
                mViewModel.reqCollection(false, 4, mVideoId.toLong())
            }
        })
    }

    @SuppressLint("NotifyDataSetChanged") private fun initObserve() {
        mViewModel.dynamicVideoLiveData.observe(this, Observer {
            if (it != null) {
                data = it
                userId = it.user.id
                isDoubleClick = it.isSupported
                if (index == 0) mActivity.setCollectionData(it.isFavorited)//设置赞属性
                mViewModel.setView(mBinding, it, tHandler, mVodPlayer, mActivity)
                if (isOpenComment) {
                    //打开评论
                    if (mPopupBinding == null) mPopupBinding = mViewModel.openCommentView(this, this)
                    mViewModel.reqCommentList(mPage, mVideoId.toLong(), topCommentId)
                    mPopupBinding?.let {
                        if (mCommentPopup == null) mCommentPopup = mViewModel.createCommentPop(mActivity, it, mBinding)
                    }
                    mCommentPopup?.showAtLocation(mBinding.llBottom, Gravity.BOTTOM, 0, 0)
                    mActivity.communityHelp.setBackgroundAlpha(mActivity)
                }
            } else {
                if (mNetErrorView == null) {
                    mNetErrorView = layoutInflater.inflate(R.layout.popup_neterror_revision, null)
                }
                mNetErrorView?.let {
                    mNetErrorViewPopup = mActivity.communityHelp.showCommentPop(mActivity, it, mBinding.llBottom, Gravity.CENTER)
                }
            }
            mBinding.ivDetailsInterval.post { mBinding.tvDetailsName.maxWidth = mViewModel.setNameTVMaxWidth(mActivity, mBinding) }

        })
        mViewModel.commentListLiveData.observe(this, Observer {
            mPopupBinding?.smartComment?.finishRefresh()
            mPopupBinding?.smartComment?.finishLoadMore()
            if (it != null) {
                mCommentBean = it
                mPopupBinding?.PBarSldComment?.visibility = View.GONE
                mPopupBinding?.BaseCommentView?.visibility = View.VISIBLE
                mPopupBinding?.BaseCommentView?.commentNetData(it, mPage)
                mPopupBinding?.tvVideoCommentHead?.text = "共${it.totalCount}条评论"
                mPage++
            }
        })
        mViewModel.followLiveData.observe(this, Observer {
            if (it.flag) {
                data?.apply {
                    user.isFocusFans = !user.isFocusFans
                    mBinding.ivDetailsFollow.isSelected = user.isFocusFans
                    com.hankol.message.HKIMUtils.followSendMsg(user.id.toInt(), it.friendState)
                }
            }
        })
        mViewModel.collectionLiveData.observe(this, Observer {
            if (it) mViewModel.upCollectionState(data, mBinding)
            data?.apply {
                if (index == 0) mActivity.setCollectionData(isFavorited)
            }
        })
        mViewModel.supportLiveData.observe(this, Observer {
            if (it) isDoubleClick = mViewModel.upSupportedState(data, mBinding)

        })
        mViewModel.friendLiveData.observe(this, Observer {
            mSharePopupWindow?.setShareFriendAdapter(mViewModel.changeFriend(it))
        })
        mViewModel.shareAddNumLD.observe(this, Observer {
            data?.let {
                it.forwardNum = it.forwardNum + 1
                mBinding.tvDetailsShare.text = NumberUtils.formatBigNum((it.forwardNum + it.outForwardNum).toString())
            }
        })
    }

    private fun loadData() {
        mViewModel.reqVideoHistoryAdd(mVideoId.toLong())
        mViewModel.reqDynamicVideoDetails(mVideoId.toLong())

    }

    override fun onClick(view: View) {
        when (view.id) {
            R.id.tv_details_topic -> data?.apply {
                if (tagIds.checkNotNull()) {
                    val hashMap = HashMap<String, Any>()
                    hashMap["tid"] = tagIds[0]
                    hashMap["tsource"] = "动态内部"
                    ARouterUtils.jump(ActivityRouter.COMMUNITY.COMMUNITY_TOPIC_DETAIL, hashMap)
                }
            }

            R.id.back, R.id.tv_neterror_other -> {
                val builder = MessageBus.Builder()
                val messageBus = builder.codeType(MessageBus.msgId_back_close).build()
                EventBus.getDefault().post(messageBus)
            }
            R.id.iv_details_head -> {
                data?.apply {
                    val hashMap = HashMap<String, Any>()
                    hashMap[BaseConstant.USER_ID] = user.id.toString()
                    ARouterUtils.jump(ActivityRouter.MINE_CENTER.USER_INFO, hashMap)
                }
            }
            R.id.iv_details_follow -> {
                if (!SpUtils.getInstance().isLogin) {
                    AppManager.getAppManager().openLoginPage()
                    return
                }
                data?.apply {
                    if (!user.isFocusFans) {
                        //详情界面只能去关注，不能取消关注。因此false时才执行事件
                        mViewModel.reqFollow(mActivity, true, 1, user.id)
                        mViewModel.sensorsFollow(SpUtils.getInstance().loadUserBean, user)
                    }
                }
            }
            R.id.ll_details_share -> {
                if (DoubleClickHelper.isOnDoubleClick()) return
                data?.let {
                    mSharePopupWindow = mViewModel.share(it, mActivity, mActivity.communityHelp)
                    mViewModel.reqFriendList()
                }
            }
            R.id.rl_details_comment -> {
                if (!SpUtils.getInstance().isLogin) {
                    AppManager.getAppManager().openLoginPage()
                    return
                }
                if (DoubleClickHelper.isOnDoubleClick()) return
                //打开评论
                showCommentPop()
            }
            R.id.ll_base_comment_empty, R.id.tv_details_comment -> {
                if (DoubleClickHelper.isOnDoubleClick()) return
                if (!SpUtils.getInstance().isLogin) {
                    AppManager.getAppManager().openLoginPage()
                    return
                }
                data?.apply {
                    if (user != null) {
                        //埋点
                        BaseConstant.loadCommentEventBusBean("动态", "内容详情页")
                        mActivity.communityHelp.openCommentActivity(
                            mActivity, 6, mVideoId, mBinding.tvDetailsComment.text.toString().trim(), user.name, false, CommentConstant.COMMENT_REQUESTCODE
                        )
                    }

                }
            }
            R.id.tv_popup_content, R.id.ll_popup_content -> {
                if (DoubleUtils.isFastDoubleClick()) {
                    return
                }
                if (!SpUtils.getInstance().isLogin) {
                    AppManager.getAppManager().openLoginPage()
                    return
                }
                mCommentPopup?.dismiss()
                data?.apply {
                    if (user != null) {
                        mActivity.communityHelp.openCommentActivity(
                            mActivity, 6, mVideoId, mBinding.tvDetailsComment.text.toString().trim(), user.name, false, CommentConstant.COMMENT_REQUESTCODE
                        )
                    }
                }
            }

            R.id.tv_popup_send -> {
                mPopupBinding?.let {
                    mViewModel.addComment(6, mVideoId, it.tvPopupContent, mActivity, this)
                }
            }
            R.id.tv_neterror_again -> {
                loadData()
                mNetErrorViewPopup?.let {
                    if (it.isShowing) it.dismiss()
                }
            }
            R.id.iv_details_fullscreen -> {
                if (mBinding.ivDetailsFullscreen.isSelected) {
                    //退出全屏
                    mBinding.llTools.visibility = View.VISIBLE
                    mBinding.llVideoIntroduce.visibility = View.VISIBLE
                    mBinding.ivDetailsFullscreen.isSelected = false
                    mBinding.ivDetailsFullscreen.setImageResource(R.drawable.ic_video_fullscreen)
                } else {
                    //全屏幕
                    mBinding.llTools.visibility = View.GONE
                    mBinding.llVideoIntroduce.visibility = View.GONE
                    mBinding.ivDetailsFullscreen.isSelected = true
                    mBinding.ivDetailsFullscreen.setImageResource(R.drawable.ic_video_smallscreen)
                }
            }
            R.id.tv_details_playSpeed -> {
                when (mBinding.tvDetailsPlaySpeed.text.toString()) {
                    //当为 1.0x速度被点击的时候，触发下一个倍速。
                    playSpeedList[0] -> {
                        mBinding.tvDetailsPlaySpeed.text = playSpeedList[1]
                        mVodPlayer.setRate(1.5F)
                    }
                    playSpeedList[1] -> {
                        mBinding.tvDetailsPlaySpeed.text = playSpeedList[2]
                        mVodPlayer.setRate(2.0F)
                    }
                    playSpeedList[2] -> {
                        mBinding.tvDetailsPlaySpeed.text = playSpeedList[3]
                        mVodPlayer.setRate(0.5F)
                    }
                    playSpeedList[3] -> {
                        mBinding.tvDetailsPlaySpeed.text = playSpeedList[0]
                        mVodPlayer.setRate(1.0F)
                    }
                }
            }
        }
    }

    private fun showCommentPop() {
        if (mPopupBinding == null) {
            mPopupBinding = mViewModel.openCommentView(this, this)
            if (mCommentPopup == null) {
                mViewModel.reqCommentList(mPage, mVideoId.toLong(), 0)
                mCommentPopup = mViewModel.createCommentPop(mActivity, mPopupBinding!!, mBinding)
            }
        }
        mCommentPopup?.showAtLocation(mBinding.llBottom, Gravity.BOTTOM, 0, 0)
        mActivity.communityHelp.setBackgroundAlpha(mActivity)
    }

    //EventBus 接受方法
    @Subscribe(threadMode = ThreadMode.MAIN) fun onEvent(messageBus: MessageBus) {
        if (messageBus.codeType == MessageBus.msgId_follow_and_cancel) {
            mViewModel.reqDynamicVideoDetails(mVideoId.toLong())
        } else if (messageBus.codeType == MessageBus.msgId_share_success) {
            data?.let {
                mViewModel.reqAddShareNum(it.id)
            }
        }
    }

    override fun onResume() {
        super.onResume()
        if (!mVodPlayer.isPlaying) {
            mVodPlayer.resume()
            mBinding.ivDetailsPlay.isSelected = true
        }
    }


    override fun onHiddenChanged(hidden: Boolean) {
        super.onHiddenChanged(hidden)
        if (hidden) { //隐藏
            if (mVodPlayer.isPlaying) {
                mVodPlayer.pause()
                mBinding.ivDetailsPlay.isSelected = false
            }
        }
    }

    override fun onPause() {
        mViewModel.hidePlayerView(tHandler)
        mVodPlayer.pause()
        mBinding.ivDetailsPlay.isSelected = false
        super.onPause()
    }

    override fun onStop() {
        if (mVodPlayer.isPlaying) {
            mVodPlayer.pause()
            mBinding.ivDetailsPlay.isSelected = false
        }
        super.onStop()
    }

    override fun onDestroyView() {
        data?.let {
            LiveDataBus.get().with(LiveDataKey.VIDEO_COUNT, String::class.java).postValue(it.id.toString() + "," + browseNum)
            mViewModel.sensorsVideo(mActivity, it)
        }
        mVodPlayer.pause()
        mVodPlayer.stopPlay(true)
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this)
        }

        super.onDestroyView()
    }

    override fun onIActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        mPopupBinding?.let {
            it.BaseCommentView.commentOnResult(requestCode, resultCode, data)
            it.BaseCommentView.setSayContent(requestCode, resultCode, data, mBinding.tvDetailsComment, CommentConstant.COMMENT_DEF_CONTENT_VERSION_2)
            val mCommentNum: Int = it.BaseCommentView.upCommentNum(requestCode, resultCode, data, this.data!!.commentNum, mBinding.tvDetailsCommentNum)
            if (mCommentNum != -1) {
                it.tvVideoCommentHead.text = "共${mCommentNum}条评论"
                this.data!!.commentNum = mCommentNum
                sendNotifyParams(MessageBus.msgid_comment_succ, mCommentNum, this.data!!.id, null, null, null, null, null, null)
            }
            if (requestCode == CommentConstant.COMMENT_REQUESTCODE && resultCode == CommentConstant.COMMENT_RESPONSE) {
                showCommentPop()
                it.BaseCommentView.setSayContent(requestCode, resultCode, data, it.tvPopupContent, CommentConstant.COMMENT_DEF_CONTENT_VERSION_1)
                it.tvPopupSend.isSelected = data != null && !TextUtils.isEmpty(data.getStringExtra(CommentConstant.COMMENT_CONTENT))
                it.tvPopupSend.isEnabled = data != null && !TextUtils.isEmpty(data.getStringExtra(CommentConstant.COMMENT_CONTENT))
            }
            if (requestCode == CommentConstant.REQUESTCODE && this.data != null) { //Activity的
                mBinding.tvDetailsCommentNum.text = (this.data!!.commentNum + 1).toString()
                this.data!!.commentNum = this.data!!.commentNum + 1
                sendNotifyParams(MessageBus.msgid_comment_succ, this.data!!.commentNum, this.data!!.id, null, null, null, null, null, null)
            }

        }
    }

    override fun onRefresh(refreshLayout: RefreshLayout) {
        //评论刷新
        mPage = 1
        mViewModel.reqCommentList(mPage, mVideoId.toLong(), 0)
    }

    override fun onLoadMore(refreshLayout: RefreshLayout) {
        //评论加载
        mPopupBinding?.let {
            val commentNorMarAdapter: BaseCommentAdapter = it.BaseCommentView.commentAdapterType
            if (mCommentBean?.count == commentNorMarAdapter.itemCount) {
                it.smartComment.finishRefresh()
                it.smartComment.finishLoadMore()
                ToastUtils.showShort(context, "已经全部加载完成")
                return
            }
            mViewModel.reqCommentList(mPage, mVideoId.toLong(), 0)
        }
    }

    /**
     * 发布成功
     */
    override fun onPublishComplete(bean: CommentReplyBean) {
        mBinding.tvDetailsComment.text = CommentConstant.COMMENT_DEF_CONTENT_VERSION_2
        mPopupBinding?.let {
            it.tvPopupSend.isSelected = false
            it.tvPopupSend.isEnabled = false
            it.tvPopupContent.text = CommentConstant.COMMENT_DEF_CONTENT_VERSION_2
        }
        mPopupBinding?.let {
            it.BaseCommentView.commentOnResult(bean)
        }
    }

}